package com.study.springbootsecurity.util;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @author: Huangjianyun
 * @date: 2025-06-09 20:20
 */
@Slf4j
public class CookieUtil {

    /**
     * 设置cookie
     * @param response
     * @param name
     * @param value
     */
    public static void set(HttpServletResponse response,
                           String name,
                           String value,
                           int maxAge,
                           String path,
                           boolean httpOnly,
                           boolean secure){
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge); // 设置有效期（秒）
        cookie.setPath(path); // 设置路径
        cookie.setHttpOnly(httpOnly);
        cookie.setSecure(secure);
        response.addCookie(cookie); //添加cookie
    }

    /**
     *
     * @Description: 删除Cookie带cookie域名
     * @param response
     * @param cookieName
     */
    public static void deleteCookie(HttpServletResponse response,
                                    String cookieName,
                                    String path,
                                    boolean httpOnly,
                                    boolean secure) {
        doSetCookie(response, cookieName, null, false,0, path,httpOnly,secure);
//        doSetCookie(request, response, cookieName, "", -1, false);
    }


    /**
     *
     * @Description: 设置Cookie的值，并使其在指定时间内生效
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param cookieMaxage	cookie生效的最大秒数
     * @param isEncode
     */
    private static final void doSetCookie(HttpServletResponse response,
                                          String cookieName,
                                          String cookieValue,
                                          boolean isEncode,
                                          int cookieMaxage,
                                          String path,
                                          boolean httpOnly,
                                          boolean secure) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            cookie.setMaxAge(cookieMaxage);
//            if (null != request) {// 设置域名的cookie
//                String domainName = getDomainName(request);
//                log.info("========== domainName: {} ==========", domainName);
//                if (!"localhost".equals(domainName)) {
//                    cookie.setDomain(domainName);
//                }
//            }
            cookie.setHttpOnly(httpOnly);
            cookie.setSecure(secure);
            cookie.setPath(path);
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取cookie
     * @param request
     * @param name
     * @return
     */
    public static Cookie get(HttpServletRequest request,
                             String name){
        Map<String, Cookie> cookieMap = readCookieMap(request);
        if(cookieMap.containsKey(name)){  //判断cookieMap是否含有该key
            return cookieMap.get(name);
        }else{
            return null;
        }

    }

    /**
     * 将cookie封装成map
     * @param request
     * @return
     */
    private static Map<String, Cookie> readCookieMap(HttpServletRequest request){
        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();        //获取所有的cookie值
        if(cookies != null){
            for (Cookie cookie : cookies){
                cookieMap.put(cookie.getName(),cookie);
            }
        }
        return cookieMap;
    }
}
